package org.example.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.example.backend.constant.ResultCode;
import org.example.backend.dto.PageResult;
import org.example.backend.dto.Result;
import org.example.backend.entity.Category;
import org.example.backend.exception.BusinessException;
import org.example.backend.mapper.CategoryMapper;
import org.example.backend.mapper.ProductMapper;
import org.example.backend.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 商品分类控制器
 * 提供分类查询、新增、修改、删除等功能
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryMapper categoryMapper;
    
    @Autowired
    private ProductMapper productMapper;

    /**
     * 分页查询分类列表
     * @param current 当前页码
     * @param size 每页大小
     * @param name 分类名称（可选，模糊查询）
     * @param status 状态（可选，精确查询）
     * @return 分页结果
     */
    @GetMapping("/page")
    public ResponseEntity<Result<PageResult<Category>>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status) {
        
        Page<Category> page = new Page<>(current, size);
        
        LambdaQueryWrapper<Category> queryWrapper = Wrappers.<Category>lambdaQuery()
                .like(StringUtils.isNotBlank(name), Category::getName, name)
                .eq(status != null, Category::getStatus, status)
                .orderByAsc(Category::getSort);
        
        Page<Category> categoryPage = categoryMapper.selectPage(page, queryWrapper);
        
        return ResponseUtil.success(new PageResult<>(categoryPage.getTotal(), categoryPage.getRecords()));
    }
    
    /**
     * 获取所有可用分类
     * @return 分类列表
     */
    @GetMapping("/list")
    public ResponseEntity<Result<List<Category>>> list() {
        List<Category> categories = categoryMapper.selectList(
                Wrappers.<Category>lambdaQuery()
                        .eq(Category::getStatus, 1)
                        .orderByAsc(Category::getSort)
        );
        return ResponseUtil.success(categories);
    }
    
    /**
     * 获取分类详情
     * @param id 分类ID
     * @return 分类详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Result<Category>> getById(@PathVariable Long id) {
        Category category = categoryMapper.selectById(id);
        if (category == null) {
            return ResponseUtil.notFound("分类不存在");
        }
        return ResponseUtil.success(category);
    }
    
    /**
     * 新增分类
     * @param category 分类信息
     * @return 操作结果
     */
    @PostMapping
    public ResponseEntity<Result<Void>> save(@Valid @RequestBody Category category) {
        // 检查分类名称是否已存在
        Long count = categoryMapper.selectCount(Wrappers.<Category>lambdaQuery().eq(Category::getName, category.getName()));
        if (count > 0) {
            throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "分类名称已存在");
        }
        
        categoryMapper.insert(category);
        return ResponseUtil.created();
    }
    
    /**
     * 修改分类
     * @param category 分类信息
     * @return 操作结果
     */
    @PutMapping
    public ResponseEntity<Result<Void>> update(@Valid @RequestBody Category category) {
        if (category.getId() == null) {
            return ResponseUtil.badRequest("ID不能为空");
        }
        
        Category existCategory = categoryMapper.selectById(category.getId());
        if (existCategory == null) {
            return ResponseUtil.notFound("分类不存在");
        }
        
        // 检查分类名称是否已被其他分类使用
        if (!existCategory.getName().equals(category.getName())) {
            Long count = categoryMapper.selectCount(
                    Wrappers.<Category>lambdaQuery()
                            .eq(Category::getName, category.getName())
                            .ne(Category::getId, category.getId())
            );
            if (count > 0) {
                throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "分类名称已存在");
            }
        }
        
        categoryMapper.updateById(category);
        return ResponseUtil.success();
    }
    
    /**
     * 删除分类
     * @param id 分类ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Result<Void>> delete(@PathVariable Long id) {
        Category category = categoryMapper.selectById(id);
        if (category == null) {
            return ResponseUtil.notFound("分类不存在");
        }
        
        // 检查是否有商品关联该分类
        Long count = productMapper.selectCount(Wrappers.<org.example.backend.entity.Product>lambdaQuery()
                .eq(org.example.backend.entity.Product::getCategoryId, id));
        if (count > 0) {
            throw new BusinessException(ResultCode.BUSINESS_ERROR, "该分类下有关联商品，无法删除");
        }
        
        categoryMapper.deleteById(id);
        return ResponseUtil.success();
    }
    
    /**
     * 更新分类状态
     * @param id 分类ID
     * @param status 状态值（0-禁用，1-启用）
     * @return 操作结果
     */
    @PutMapping("/status")
    public ResponseEntity<Result<Void>> updateStatus(@RequestParam Long id, @RequestParam Integer status) {
        Category category = categoryMapper.selectById(id);
        if (category == null) {
            return ResponseUtil.notFound("分类不存在");
        }
        
        Category updateCategory = new Category();
        updateCategory.setId(id);
        updateCategory.setStatus(status);
        categoryMapper.updateById(updateCategory);
        
        return ResponseUtil.success();
    }
} 